﻿using Modbus.Device;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace IndustrialControlLibrary
{
    public partial class HMI_I_Switch : UserControl
    {
        public HMI_I_Switch()
        {
            InitializeComponent();
        }


        private bool _isOpen;
        private bool _isAssigned = false;
        public dynamic modbusMaster;

        public byte slaveAddress;
        public ushort registerAdderss;

        /// <summary>
        /// 将建立好的链接传入控件
        /// </summary>
        /// <param name="connetionMaster"></param>
        public void assignMaster(dynamic connetionMaster)
        {
            modbusMaster = connetionMaster;
            _isAssigned = true;
            string[] _stringAddress = this.address.Split(':');
            slaveAddress = Convert.ToByte(_stringAddress[0]);
            registerAdderss = (ushort)(Convert.ToInt32(_stringAddress[1].Remove(0,1)) - 1);
        }


        /// <summary>
        /// 按钮颜色显示
        /// </summary>
        private void judgeColor()
        {
            if (_isOpen)
            {
                this.btn_open.BackColor = System.Drawing.Color.Green;
                this.btn_close.BackColor = System.Drawing.Color.Gray;
            }
            else
            {
                this.btn_close.BackColor = System.Drawing.Color.Red;
                this.btn_open.BackColor = System.Drawing.Color.Gray;
            }
        }


        private void btn_open_Click(object sender, EventArgs e)
        {
            if (_isAssigned)
            {
                modbusMaster.WriteSingleCoil(slaveAddress, registerAdderss, true);
                _isOpen = true;
                judgeColor();
            }
        }

        private void btn_close_Click(object sender, EventArgs e)
        {
            if (_isAssigned)
            {
                modbusMaster.WriteSingleCoil(slaveAddress, registerAdderss, false);
                _isOpen = false;
                judgeColor();
            }
        }
    }
}
